package com.cykj.web.controller.posbiz;

import com.cykj.common.core.domain.AjaxResult;
import com.cykj.pos.domain.BizCrownSpecial;
import com.cykj.pos.domain.BizMerchant;
import com.cykj.pos.domain.BizShareDetail;
import com.cykj.pos.profit.dto.ShareDetailDTO;
import com.cykj.pos.service.IBizMerchantService;
import com.cykj.pos.service.IBizShareDetailService;
import com.cykj.pos.util.ShareDetailUtil;
import com.cykj.pos.util.SpecialGPAPersonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分润明细Controller
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/share/detail")
@Api(tags = "分润明细")
public class BizShareDetailController {

    private final IBizShareDetailService bizShareDetailService;

    private final IBizMerchantService merchantService;

    /**
     * 分润明细列表
     */
    @ApiOperation(value = "获取分润明细列表")
    @PostMapping("/list")
    public AjaxResult shareDetailList(@RequestBody ShareDetailDTO shareDetailDTO){
        AjaxResult ajaxResult = AjaxResult.success("获取分润");
        // 查询所有合作伙伴的merch_id user_id merch_name
        List<ShareDetailDTO> merchantInfo = bizShareDetailService.queryMerchantInfo();
        for (int i=0;i<merchantInfo.size();i++){
            // 通过parent_id 去查上级的名字
            ShareDetailDTO shareDetailDTO1 = bizShareDetailService.queryParentName(merchantInfo.get(i).getParentId());
            merchantInfo.get(i).setParentName(shareDetailDTO1.getParentName());// 父级名称
            merchantInfo.get(i).setStartTime(shareDetailDTO.getStartTime());// 存开始时间
            merchantInfo.get(i).setEndTime(shareDetailDTO.getEndTime());// 存结束时间
        }
        String orderId = ShareDetailUtil.createOrderId();
        // 把所有人的循环生成分润明细
        for(int i=0;i<merchantInfo.size();i++){
            // 先来一个sql 查出自身交易笔数（除去储蓄卡的）、金额（除去储蓄卡）、闪付金额、刷卡金额（除去储蓄卡的）、扫码金额
            BizShareDetail bizShareDetail = bizShareDetailService.queryOwnDealInfo(merchantInfo.get(i));
            bizShareDetail.setOwnDepositCard(bizShareDetail.getOwnSlotCard().subtract(bizShareDetail.getOwnCreditCard()));// 自身储蓄卡
            // 把这个人的merch_id 姓名存入
            bizShareDetail.setMerchId(merchantInfo.get(i).getMerchId());
            bizShareDetail.setMerchName(merchantInfo.get(i).getMerchName());
            bizShareDetail.setParentName(merchantInfo.get(i).getParentName());// 存入父级的姓名
            bizShareDetail.setParentId(merchantInfo.get(i).getParentId());// 存入父级id
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM- dd HH:mm:ss");
            bizShareDetail.setCreateTime(dateFormat.format(date));
            bizShareDetail.setOrderId(orderId);// 生成订单号
            // 第二个sql 查出自身交易笔数（除去储蓄卡的）、金额（除去储蓄卡）、闪付金额、刷卡金额（除去储蓄卡的）、扫码金额
            BizShareDetail bizParentDetail = bizShareDetailService.queryParentDealInfo(merchantInfo.get(i));
            bizShareDetail.setDownAllDealNum(bizParentDetail.getDownAllDealNum()-bizShareDetail.getOwnDealNum());
            bizShareDetail.setDownAllDealSum(bizParentDetail.getDownAllDealSum().subtract(bizShareDetail.getOwnDealSum()));
            bizShareDetail.setDownAllQuickPass(bizParentDetail.getDownAllQuickPass().subtract(bizShareDetail.getOwnQuickPass()));
            bizShareDetail.setDownAllSlotCard(bizParentDetail.getDownAllSlotCard().subtract(bizShareDetail.getOwnSlotCard()));
            bizShareDetail.setDownAllScanPay(bizParentDetail.getDownAllScanPay().subtract(bizShareDetail.getOwnScanPay()));
            bizShareDetail.setDownAllCreditCard(bizParentDetail.getDownAllCreditCard().subtract(bizShareDetail.getOwnCreditCard()));
            // bizShareDetail.setDownAllDepositCard(bizShareDetail.getDownAllSlotCard().subtract(bizShareDetail.getDownAllCreditCard()));// 下级储蓄卡交易
            /*// 要求出用户加上交易量 加上 伙伴的一层的交易量
            BigDecimal bigDealNum = bizParentDetail.getDownAllDealSum();// 用户交易总量
            // 现在要用刷信用卡 扫码 闪付
            BigDecimal fenrunSum = bizParentDetail.getDownAllDealSum();// 所有交易量减去储蓄卡
            // 伙伴的交易量
            List<BigDecimal> list = null;
            // 查询下线的所有标识merch_id
            List<ShareDetailDTO> list1 = bizShareDetailService.queryParentMerchId(merchantInfo.get(i));
            List<ShareDetailDTO> list2 = new ArrayList<ShareDetailDTO>();
            list2.add(null);
            list1.removeAll(list2);// 去除空元素
            // 再去查下线的自身交易量
            for(int a=0;a<list1.size();a++){
                list1.get(a).setStartTime(shareDetailDTO.getStartTime());
                list1.get(a).setEndTime(shareDetailDTO.getEndTime());
                // 查询每个下线伙伴的自身交易总量
                BizShareDetail bizShareDetail1 = bizShareDetailService.queryParentDealSum(list1.get(a));
                // 查询每个下线伙伴的刷卡交易总量
                BizShareDetail bizShareDetail2 = bizShareDetailService.queryParentDealSlotCard(list1.get(a));
                list1.get(a).setDealSum(bizShareDetail1.getDownAllDealSum());// 全部交易量除去储蓄卡的
                list1.get(a).setDealSlotCardSum(bizShareDetail2.getDownAllDealSum());// 只有刷卡的
            }
            // 求交易分润
            BizShareDetail bizShareDetail1 = ShareDetailUtil.dealShare(fenrunSum);
            List<BigDecimal> num = ShareDetailUtil.parentDealShare(list1);
            // 求分润差 来计算最终的分润
            BigDecimal fenrun = new BigDecimal(0);
            for (int b=0;b<num.size();b++){
                fenrun = fenrun.add(num.get(b));
            }
            bizShareDetail.setDealShare(bizShareDetail1.getDealShare().subtract(fenrun));// 把分润结果存入最终的结果
            bizShareDetail.setDealShareRatio(bizShareDetail1.getDealShareRatio());// 把分润比例存入最终结果
            // 管理津贴
            BigDecimal allowance = ShareDetailUtil.managerAllowance(list1);
            bizShareDetail.setManaAllow(allowance);// 把管理津贴存入最终的结果
            // 钻石奖金 只要刷卡的
            BigDecimal diamondMoney = ShareDetailUtil.diamondBonus(list1);
            bizShareDetail.setDiamondBonus(diamondMoney);// 把钻石奖金存入最终结果
            // 皇冠奖 先把交易总额查出来 只有刷信用卡的
            BigDecimal allDealSum = bizShareDetailService.queryTransAmount(merchantInfo.get(i));
            BizShareDetail bizShareDetailCrown = ShareDetailUtil.crownAward(allDealSum);
            bizShareDetail.setCrownAward(bizShareDetailCrown.getCrownAward());// 把皇冠奖励存入最终结果
            bizShareDetail.setCrownRatio(bizShareDetailCrown.getCrownRatio());// 把皇冠奖励率存入最终结果
            // 分红奖励
            List<ShareDetailDTO> list3 = bizShareDetailService.queryParentMerchId(shareDetailDTO);//查他的伙伴
            list3.removeAll(list2);// 去除空元素
            for (int c=0;c<list3.size();c++){
                BigDecimal bigDecimal = bizShareDetailService.queryParentAllDealSum(list1.get(c));
                list3.get(c).setDealSum(bigDecimal);
            }
            BigDecimal shareOutBonus = ShareDetailUtil.participation(list3,allDealSum);
            bizShareDetail.setUserBonusers(shareOutBonus);// 把分红的奖金存入最终结果
            // 分润补贴
            BigDecimal shareSubsidy = new BigDecimal("0");// 分润补贴默认都是零
            bizShareDetail.setShareSubsidy(shareSubsidy); // 每个人默认分润补贴都是零
            // 五项总计
            BigDecimal fourAggregate = bizShareDetail.getDealShare().add(bizShareDetail.getManaAllow()).add(bizShareDetail.getDiamondBonus()).add(bizShareDetail.getCrownAward().add(bizShareDetail.getShareSubsidy()));
            bizShareDetail.setFourAggregate(fourAggregate); // 把五项项总计存入最终结果
            BigDecimal taxRate = new BigDecimal("0.091"); // 税率
            BigDecimal fourAfterTax = fourAggregate.subtract(fourAggregate.multiply(taxRate));
            bizShareDetail.setFourAfterTax(fourAfterTax);// 把五项税后存入最终结果
            bizShareDetail.setCheckStatus(0L);*/
            // 把生成的分润信息存入数据库中
            bizShareDetailService.saveShareDetail(bizShareDetail);
        }
        return ajaxResult;
    }

    @PostMapping("/ratio")
    public AjaxResult saveRatio(@RequestBody ShareDetailDTO shareDetailDTO){
        List<BizShareDetail> list = bizShareDetailService.queryAllShareByOrderId(shareDetailDTO.getOrderId());
        for (int i = 0;i<list.size();i++){
            BizShareDetail bizShareDetail1 = ShareDetailUtil.dealRatio(list.get(i).getOwnDealSum().add(list.get(i).getDownAllDealSum()));
            list.get(i).setDealShareRatio(bizShareDetail1.getDealShareRatio());
            bizShareDetailService.saveShareDetail(list.get(i));
        }
        return AjaxResult.success();
    }

    // 根据姓名把商户的merch_id存进去
    @PostMapping("/save/merch")
    public AjaxResult saveMerchByName(){
        List<BizCrownSpecial> list = bizShareDetailService.querySpecialCrown();
        for (BizCrownSpecial bizCrownSpecial : list){
            BizMerchant bizMerchant = merchantService.getMerchantByName(bizCrownSpecial.getMerchName());
            bizCrownSpecial.setMerchId(bizMerchant.getMerchId());
            bizShareDetailService.updateCrownSpecial(bizCrownSpecial);
        }
        return AjaxResult.success();
    }

    // 计算皇冠奖励特殊人群
    @PostMapping("/get/crown")
    public AjaxResult getSpecialCrown(@RequestBody ShareDetailDTO shareDetailDTO){
        AjaxResult ajaxResult = AjaxResult.success("计算特殊皇冠奖励");
        List<BizShareDetail> list1 = bizShareDetailService.queryAllShareByOrderId(shareDetailDTO.getOrderId());
        for (int i=0;i<list1.size();i++){
            BigDecimal finalDeal = list1.get(i).getFinalDealProfit();// 最终分润
            BigDecimal finalCrown = list1.get(i).getFinalCrownProfit();// 最终皇冠
            list1.get(i).setFourAggregate(finalDeal.add(finalCrown));// 最终五项总计
            BigDecimal bigDecimal = new BigDecimal("0.91");
            list1.get(i).setFourAfterTax(list1.get(i).getFourAggregate().multiply(bigDecimal));// 最终五项税后
            bizShareDetailService.saveOrUpdate(list1.get(i));// 存入最终五项总计
        }
        return ajaxResult;
    }

    @PostMapping("/calculate")
    public AjaxResult getCalculate(@RequestBody ShareDetailDTO shareDetailDTO){
        AjaxResult ajaxResult = AjaxResult.success("计算分润补贴");
        BigDecimal zeroFour = new BigDecimal("0.00040");
        BigDecimal zeroThree = new BigDecimal("0.0003");
        BigDecimal four = new BigDecimal("4");
        BigDecimal three = new BigDecimal("3");
        List<BizShareDetail> list = bizShareDetailService.queryAllShareByOrderId(shareDetailDTO.getOrderId());
        for (BizShareDetail bizShareDetail : list){
            if (bizShareDetail.getCrownRatio().equals(zeroFour)){// 说明是万四
                BigDecimal bigDecimal = bizShareDetail.getFinalCrownProfit();// 最终分润
                BigDecimal overCrown = bigDecimal.divide(four);// 除以四
                bizShareDetail.setCrownAward(overCrown.multiply(three));
                bizShareDetail.setCrownRatio(zeroThree);// 分润率
                bizShareDetail.setShareSubsidy(overCrown);// 分润补贴
                bizShareDetailService.saveOrUpdate(bizShareDetail);// 存入最终五项总计
            }
        }
        return ajaxResult;
    }
    /**
     * 获取个人最终分润信息列表
     * @param shareDetailDTO
     * @return
     */
    @PostMapping("/calcFinalShare")
    public AjaxResult getShareFinalList(@RequestBody ShareDetailDTO shareDetailDTO){
        AjaxResult ajaxResult = AjaxResult.success("获取个人最终分润信息列表");
        String orderId = shareDetailDTO.getOrderId();// 订单号
        // 通过订单号 计算分润信息
        boolean b = bizShareDetailService.calcFinalShare(orderId);
        if(b){
            ajaxResult.put("data","success");
        }else{
            ajaxResult.put("data","生成失败");
        }
        return ajaxResult;
    }
}
